/**
 * @file entry
 * @author tangyue(736185378@qq.com)
 */

import Vue from "vue";
import Meta from "vue-meta";

import { createRouter } from "@/.lavas/router";
import { createStore } from "@/.lavas/store";
import AppComponent from "./App.vue";
import axios from "axios";
import VueAxios from "vue-axios";

import Icon from "vue-awesome/components/Icon.vue";

Date.prototype.Format = function(fmt) {
    //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(
            RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1
                    ? o[k]
                    : ("00" + o[k]).substr(("" + o[k]).length)
            );
    return fmt;
};

// 注册 Icon 组件
Vue.component("icon", Icon);
// 添加请求拦截器
axios.interceptors.request.use(config => {
    // 在发送请求之前做些什么
    config.headers.common["token"] = localStorage.token || "";
    config.headers.common["account"] = localStorage.account || "";
    config.baseURL = `${window.location.origin}/`
    return config;
});

Vue.use(Meta);
Vue.use(VueAxios, axios);

Vue.config.productionTip = false;

export function createApp() {
    let router = createRouter();
    let store = createStore();
    let App = Vue.extend({
        router,
        store,
        ...AppComponent
    });
    // 添加响应拦截器
    axios.interceptors.response.use(
        response => {
            // 对响应数据做点什么
            if (response.data.ok === false) console.log(response);
            return response;
        },
        error => {
            // 对响应错误做点什么
            if (error.response.status === 666) router.push({ name: "user" });
            return Promise.reject(error);
        }
    );
    return { App, router, store };
}

if (module.hot) {
    module.hot.accept();
}
